package verify;

import org.apache.catalina.Session;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;

public class SafeCode extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1626673439350527994L;
    DataBase dataBase = new DataBase();
    PreparedStatement stmt = null;
    ResultSet result = null;
    //    private static char code[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
    public SafeCode() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置输出类型和浏览器不保存缓存
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache");

        //创建图片对象
        int width = 60, height = 20;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = image.getGraphics();

        //生成随机数
        Random random = new Random();
        String s = "";
//        StringBuffer s = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            s += random.nextInt(10);
//            s+=String.valueOf(code[random.nextInt(code.length)]);
//            char code = codeChars.charAt(random.nextInt(codeChars.length()));
//            s.append(code);
        }

        //把随机数存到Session里面，便于等下比较
        HttpSession session = request.getSession();
        session.setAttribute("code", s);

        //随机生成颜色  Color color =  new Color(255,255,255) ;     random.nextInt(256)的值范围是0~255
        Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
//        g.setColor(color);
//        g.fillRect(0, 0, width, height);
        //把随机数写到图片上
        String a = null;
        Font font = new Font(a, Font.ITALIC, 18);
        g.setColor(color);
        g.setFont(font);
//        g.drawString(String.valueOf(s), 10,height-5);
        g.drawString(s, 10, height - 5);
        g.dispose();    //关闭画笔

        //把图片送到客户端
        ServletOutputStream output = response.getOutputStream();
        ImageIO.write(image, "JPEG", output);
        output.flush();   //关闭输出流

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
//        this.doGet(request,response);
            String name = request.getParameter("name");
            String pwd = request.getParameter("password");
//            PrintWriter writer=new PrintWriter(response.getOutputStream());
            request.setAttribute("name", name);
            request.setAttribute("password", pwd);
        request.setAttribute("loginError", "你输入的用户名或密码错误.");
        String inputCode = request.getParameter("inputcode");
            request.setAttribute("inputcode", inputCode);

            HttpSession session = request.getSession();
            String code = (String) session.getAttribute("code");
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            dataBase.setConnection("jdbc:mysql://127.0.0.1:3306/servlettest?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC",
                    "zhanghu", "huayang520");

            String sql = "select name1,password1 from login ";

            stmt = dataBase.connection.prepareStatement(sql);

//            smtp.setString(1, "name1");
//            smtp.setString(2, "password1");
            result = stmt.executeQuery();
            //System.out.println(result);
            while (true) {
                if (result.next()) {
                    int i = 0;

                    String username[] = new String[10];//用户名数组
                    String password[] = new String[10];//密码数组
                    username[i] = result.getString(1);
                    password[i] = result.getString(2);
                    if (username[i].equals(name) && password[i].equals(pwd) && code.equals(inputCode)) {
                        request.getRequestDispatcher("/welcome.jsp").forward(request, response);
                        return;
                    } else if (!username[i].equals(name) || !password[i].equals(pwd) || !code.equals(inputCode)) {
                        i++;
                        continue;

                    }
                } else {
//                    writer.print("<script language='javascript'>alert('UserName Wrong!!');window.location.href='index.jsp';</script>");
                    request.getRequestDispatcher("/mistake.jsp").forward(request, response);
                    return;
                      }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
//        String name=request.getParameter("name");
//        String pwd=request.getParameter("password");
//        //PrintWriter writer=new PrintWriter(response.getOutputStream());
//        request.setAttribute("name", name);
//        request.setAttribute("password", pwd);
//
//        String inputCode = request.getParameter("inputcode");
//        request.setAttribute("inputcode", inputCode);
//
//        HttpSession session=request.getSession();
//        String code= (String) session.getAttribute("code");
//        if ("123".equals(name)&&"123".equals(pwd)&&code.equals(inputCode)){
//            //RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp").forward(req,resp);//传递servlet的入口参数
//            request.getRequestDispatcher("/welcome.jsp").forward(request, response);
//            //resp.sendRedirect("http://192.168.0.181:8080/index.jsp?name=123");
//            //writer.print("欢迎 "+name);
//        }else{
//            request.getRequestDispatcher("/mistake.jsp").forward(request,response);
//            //writer.print("错误的name: "+name+"密码："+pwd);
//        }
////        this.doGet(request,response);

    }

    public void init() throws ServletException {
    }
}  